import 'dart:io';
import 'dart:typed_data';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/file_utils.dart';
import 'package:yuan_hang_app/utils/router_helper.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/views/home/view/drive/preview_attachement.dart';
import 'package:yuan_hang_app/views/home/view/drive/signature_page.dart';
import 'package:yuan_hang_app/widget/image_picker.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/string_utils.dart';
import '../../../../utils/common_req_utils.dart';
import '../../../../widget/common_attachment.dart';
import '../../../../widget/label_item.dart';
import '../../../../widget/w_toast.dart';

class DriveRegistrationDetailPage extends StatefulWidget {
  int testDriveId;

  DriveRegistrationDetailPage({super.key, required this.testDriveId});

  @override
  BaseState<DriveRegistrationDetailPage> createState() =>
      _BookDriveUpdatePageState();
}

class _BookDriveUpdatePageState extends BaseState<DriveRegistrationDetailPage> {
  final _formKey = GlobalKey<FormState>();
  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> driveTypeList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveType);
  List<Map> driveMethodList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.driveMethod);
  List<Map> saleManList = WConstant().salesmanList;

  List<Map> driveCarList = [
    {"label": "哈佛", "value": "哈佛"},
    {"label": "大众", "value": "大众"},
    {"label": "其他车辆", "value": "其他车辆"},
  ];

  //初始化试驾预约登记对象
  Map driveInfo = {};

  GlobalKey<LabelItemState>? driveMethodKey;
  GlobalKey<LabelItemState>? driveTypeKey;
  GlobalKey<LabelItemState>? cancelReasonKey;
  GlobalKey<LabelItemState>? modelKey;

  final ImagePicker _picker = ImagePicker();
  String? _driverLicenseFrontImage;
  String? _driverLicenseBackImage;
  Uint8List? imageBytes;

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "试驾登记详情",
        resizeToBottomInset: true,
        child: SingleChildScrollView(
            padding: EdgeInsets.only(top: 10.px), child: _bookDriveContent()));
  }

  Widget _bookDriveContent() {
    return Container(
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 16.px, right: 16.px, bottom: 10.px),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.px),
            color: Colors.white,
            boxShadow: const [
              BoxShadow(
                  //线框阴影线条
                  color: WColors.border,
                  offset: Offset(0, 1),
                  blurRadius: 2)
            ]),
        child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(
                height: 1.px,
              ),
              LabelItem(
                key: keyMap["driveTypeKey"],
                label: "试驾类型",
                // labelType: LabelType.LIST,
                // dataList: driveTypeList,
                value:CommonReqUtils.exchangeCodeToName2(
                    driveTypeList, StringUtils.safeGetValue(driveInfo["driveType"])) ??
                    "-"
              ),
              LabelItem(
                key: keyMap["driveMethodKey"],
                label: "试驾方式",
                // labelType: LabelType.LIST,
                // dataList: driveMethodList,
                  value:CommonReqUtils.exchangeCodeToName2(
                      driveMethodList, StringUtils.safeGetValue(driveInfo["driveMethod"])) ??
                      "-"
              ),
              LabelItem(
                  label: "试驾车型",
                  key: modelKey,
                  labelType: LabelType.DROW_DOWN,
                  dataList: modelList,
                  value: driveInfo["modelId"]),
              LabelItem(
                label: "接待顾问",
                value:   StringUtils.safeGetValue(driveInfo["saleMan"],
                    placeHolder: "未知")
              ),
              LabelItem(
                label: "客户名称",
                value: StringUtils.safeGetValue(driveInfo["customerName"]),
              ),
              LabelItem(
                label: "手机号码",
                value: StringUtils.safeGetValue(driveInfo["phone"] ?? ""),
              ),
              LabelItem(
                label: "证件号码",
                value: driveInfo["idNo"],
              ),
              LabelItem(
                label: "客户地址",
                value: driveInfo["address"],
              ),
              Padding(
                padding:
                    EdgeInsets.symmetric(horizontal: 15.px, vertical: 10.px),
                child: Row(
                  children: <Widget>[
                    _driverLicense('驾驶证主页'),
                    SizedBox(
                      width: 20.px,
                    ),
                    _driverLicense('驾驶证副页')
                  ],
                ),
              ),
              WLine(
                height: 0.5.px,
              ),
              // 试驾车辆下拉框
              LabelItem(
                label: "试驾车辆",
                value: StringUtils.safeGetValue(driveInfo["driveVehicle"]),
              ),
              // 试驾协议
              LabelItem(
                label: "试驾协议",
                labelType: LabelType.SELECT,
                value: "查看试驾协议",
                onTap: () async {
                  if (driveInfo["fileAddress"] == null ||
                      driveInfo["fileAddress"].length < 3 ||
                      driveInfo["fileAddress"][2]["testDriveAgreementList"] ==
                          null) {
                    Toast.toast("试驾协议为空！");
                    return;
                  }
                  var fileInfo =driveInfo["fileAddress"][2]["testDriveAgreementList"];
                  if (fileInfo.contains("https")) {
                    String time = DateUtil.formatDate(DateTime.now(),
                        format: "yyyyMMddHHmmss.pdf");
                    File? file = await FileUtils.getAppFile(time);
                    if (file == null) {
                      return;
                    }
                    showLoading();
                    HttpUtils().downloadFile(fileInfo, file.path).then((res) {
                      hideLoading();
                      RouteHelper.pushWidget(
                          context,
                          PreviewAttachementPage(
                            url: file.path,
                          ));
                    }).catchError((e){
                      hideLoading();
                    });
                  }else{
                    RouteHelper.pushWidget(
                        context,
                        PreviewAttachementPage(
                            url: driveInfo["fileAddress"][2]
                            ["testDriveAgreementList"]));
                  }
                },
              ),
              // GestureDetector(
              //     onTap: () {
              //       RouteHelper.pushWidget(context,
              //           PreviewAttachementPage(url: driveInfo["fileList"]));
              //     },
              //     child: SizedBox(
              //       width: 24.px, // 你的期望宽度
              //       height: 24.px, // 你的期望高度
              //       child: const Icon(
              //         Icons.attach_file,
              //         color: WColors.mainTextColor,
              //       ),
              //     )),

              LabelItem(
                label: "开始时间",
                value: StringUtils.safeGetValue(driveInfo["startDriveTime"],
                    placeHolder: "-"),
              ),
              LabelItem(
                label: "结束时间",
                value: StringUtils.safeGetValue(driveInfo["endDriveTime"],
                    placeHolder: "-"),
              ),
              LabelItem(
                label: "取消时间",
                value: StringUtils.safeGetValue(driveInfo["cancelTime"],
                    placeHolder: "-"),
              ),
              LabelItem(
                key: cancelReasonKey,
                labelType: LabelType.TEXTAREA,
                label: "取消原因",
                isEnabled: false,
                value: StringUtils.safeGetValue(driveInfo["remark"],
                    placeHolder: "-"),
              ),
            ]));
  }

  // 用于构建显示图片的Widget
  Widget _driverLicense(String label) {
    var imageFile =
        label == "驾驶证主页" ? _driverLicenseFrontImage : _driverLicenseBackImage;
    return Expanded(
        child: Column(
      children: <Widget>[
        WText(
          label,
          style: TextStyle(
              color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
        ),
        SizedBox(
          height: 10.px,
        ),
        GestureDetector(
          // onTap: () {
          //   ImagePicker.showImagePicker(
          //       context: context,
          //       onSelected: (file) {
          //         if (file != null && file.length > 0) {
          //           if (label == "驾驶证主页") {
          //             _driverLicenseFrontImage = file[0];
          //           } else {
          //             _driverLicenseBackImage = file[0];
          //           }
          //         }
          //         setState(() {});
          //       });
          // },
          child: imageFile == null
              ? getDriveUrl(label) == ""
                  ? const SizedBox()
                  : Image.network(
                      getDriveUrl(label),
                      fit: BoxFit.cover,
                      width: SizeUtils.screenW() / 2 - 20.px,
                      height: 100.px,
                    )
              : Image.file(
                  File(imageFile),
                  fit: BoxFit.cover,
                  width: SizeUtils.screenW() / 2 - 20.px,
                  height: 100.px,
                ),
        )
      ],
    ));
  }

  String getDriveUrl(label) {
    return label == "驾驶证主页"
        ? (driveInfo["fileAddress"] != null &&
                driveInfo["fileAddress"].length > 1)
            ? driveInfo["fileAddress"][0]["frontPictureList"]
            : ""
        : (driveInfo["fileAddress"] != null &&
                driveInfo["fileAddress"].length > 2)
            ? driveInfo["fileAddress"][1]["backPictureList"]
            : "";
  }

  void _printFormData() {
    print("修改的对象是：$driveInfo");
  }

  Map<String, GlobalKey<LabelItemState>?> keyMap = {};

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    cancelReasonKey = GlobalKey(debugLabel: "remark");

    driveTypeKey = GlobalKey(debugLabel: "driveTypeKey");
    keyMap["driveTypeKey"] = driveTypeKey;

    driveMethodKey = GlobalKey(debugLabel: "driveMethodKey");
    keyMap["driveMethodKey"] = driveMethodKey;

    modelKey = GlobalKey(debugLabel: "modelKey");

    showLoading();
    HttpUtils()
        .get("${Api.getTestDriveDetail}/${widget.testDriveId}")
        .then((data) {
      hideLoading();
      if (data.resultCode == 200) {
        print("试驾详情查询返回结果");
        print(data.data);
        driveInfo = data.data;
        setState(() {});
        driveMethodKey!.currentState?.refreshList(WConstant.driveMethodList,
            StringUtils.safeGetValue(driveInfo["driveMethod"]));
        cancelReasonKey!.currentState?.refreshInput(driveInfo["remark"] ?? "");
        driveTypeKey!.currentState?.refreshList(WConstant.driveTypeList,
            StringUtils.safeGetValue(driveInfo["driveType"]));
        modelKey!.currentState?.refreshList(modelList, driveInfo["modelId"]);
      } else {
        Toast.toast(data.errMsg ?? "");
      }
    }).catchError((e) {
      hideLoading();
    });
  }
}
